﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace LambdaToSql.EntityModel
{
    /// <summary>
    /// 数据库上下文对象
    /// </summary>
    [Serializable]
    [DataContract]
    public class DbContext
    {
        /// <summary>
        /// 连接字符串名称
        /// </summary>
        [DataMember]
        public string ConnectionStringName { get; set; }

        /// <summary>
        /// 数据库类型 默认SqlServer 
        /// </summary>
        [DataMember]
        public SqlType? SqlType { get; set; }

        /// <summary>
        /// 在 SQL Server 数据库中处理的 Transact-SQL 事务
        /// </summary>
        [DataMember]
        public SqlTransaction Trans { get; set; }

        /// <summary>
        /// 事务关联的SqlConnection 对象，或者如果该事务不再有效，则为 null。 
        /// </summary>
        [DataMember]
        internal SqlConnection TransConnection { get; set; }

        /// <summary>
        /// 连接字符串,可以外部直接指定
        /// <para>ConnectionStringName为空 本属性才生效</para>
        /// </summary>
        [DataMember]
        public string ConnectionString { get; set; }

        /// <summary>
        /// 数据库表结构 字典结构
        /// </summary>
        [DataMember]
        public Dictionary<string, LambdaToSql.EntityModel.Table> Table { get; set; }

        /// <summary>
        /// 数据库表结构 List结构
        /// </summary>
        [DataMember]
        public List<LambdaToSql.EntityModel.Table> TableList
        {
            get
            {
                return this.Table.Select(ex => ex.Value).ToList();
            }
        }

        /// <summary>
        /// 数据库处理帮助类接口
        /// </summary>
        public LambdaToSql.DbHelper.IDBhelper DbHelper
        {
            get;
            private set;
        }


        /// <summary>
        /// 初始化注册
        /// </summary>
        public void InitRegister()
        {
            if (string.IsNullOrEmpty(this.ConnectionStringName) && string.IsNullOrEmpty(this.ConnectionString))
            {
                this.ConnectionStringName = "ConnectionString";
            }
            if (this.SqlType == null)
            {
                this.SqlType = LambdaToSql.EntityModel.SqlType.MsSqlServer;
            }
            if (string.IsNullOrEmpty(this.ConnectionString))
            {
                this.ConnectionString = ConfigurationManager.ConnectionStrings[this.ConnectionStringName].ToString();
            }

            var obj = (LambdaToSql.TableStruct.BaseTable)LambdaToSql.FrameWork.Tools.GetReflectionObj("LambdaToSql", "LambdaToSql.TableStruct." + this.SqlType);
            obj.Context = this;
            this.Table = obj.DicTable;

            this.DbHelper = new LambdaToSql.DbHelper.Factory() { Context = this }.IDBhelper;
        }
    }
}
